"use client"

import { useState } from "react"
import { motion } from "framer-motion"
import { useAuth } from '@/contexts/auth-context'
import Link from "next/link"
import { Play, Clock, Users, Star, Award, TrendingUp, Filter, Search } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Progress } from "@/components/ui/progress"

const mockCourses = [
  {
    id: 1,
    title: "机器学习入门：从零到Kaggle竞赛",
    instructor: "Dr. Andrew Ng",
    avatar: "/placeholder.svg?height=40&width=40",
    duration: "8小时",
    students: 15420,
    rating: 4.8,
    level: "初级",
    category: "Machine Learning",
    price: "免费",
    thumbnail: "/placeholder.svg?height=200&width=300",
    description: "全面学习机器学习基础，直接应用到Kaggle竞赛中",
    progress: 0,
    tags: ["Python", "Scikit-learn", "Pandas"],
  },
  {
    id: 2,
    title: "深度学习与计算机视觉实战",
    instructor: "李飞飞",
    avatar: "/placeholder.svg?height=40&width=40",
    duration: "12小时",
    students: 8900,
    rating: 4.9,
    level: "高级",
    category: "Deep Learning",
    price: "¥299",
    thumbnail: "/placeholder.svg?height=200&width=300",
    description: "掌握CNN、RNN等深度学习技术，解决实际视觉问题",
    progress: 35,
    tags: ["TensorFlow", "PyTorch", "OpenCV"],
  },
  {
    id: 3,
    title: "Web3开发完整指南",
    instructor: "Vitalik Buterin",
    avatar: "/placeholder.svg?height=40&width=40",
    duration: "10小时",
    students: 6750,
    rating: 4.7,
    level: "中级",
    category: "Blockchain",
    price: "¥199",
    thumbnail: "/placeholder.svg?height=200&width=300",
    description: "从智能合约到DApp开发，全面掌握Web3技术栈",
    progress: 0,
    tags: ["Solidity", "React", "Web3.js"],
  },
  {
    id: 4,
    title: "数据科学竞赛策略与技巧",
    instructor: "Jeremy Howard",
    avatar: "/placeholder.svg?height=40&width=40",
    duration: "6小时",
    students: 12300,
    rating: 4.8,
    level: "中级",
    category: "Data Science",
    price: "免费",
    thumbnail: "/placeholder.svg?height=200&width=300",
    description: "学习顶级数据科学家的竞赛策略和实战技巧",
    progress: 80,
    tags: ["Python", "Jupyter", "Visualization"],
  },
  {
    id: 5,
    title: "React全栈开发实战",
    instructor: "Dan Abramov",
    avatar: "/placeholder.svg?height=40&width=40",
    duration: "15小时",
    students: 9800,
    rating: 4.6,
    level: "中级",
    category: "Web Development",
    price: "¥399",
    thumbnail: "/placeholder.svg?height=200&width=300",
    description: "从React基础到全栈应用开发，打造现代Web应用",
    progress: 0,
    tags: ["React", "Node.js", "MongoDB"],
  },
  {
    id: 6,
    title: "AI大模型应用开发",
    instructor: "Sam Altman",
    avatar: "/placeholder.svg?height=40&width=40",
    duration: "8小时",
    students: 11200,
    rating: 4.9,
    level: "高级",
    category: "AI/LLM",
    price: "¥499",
    thumbnail: "/placeholder.svg?height=200&width=300",
    description: "掌握GPT、Claude等大模型的应用开发技巧",
    progress: 0,
    tags: ["OpenAI", "LangChain", "Python"],
  },
]

const mockPaths = [
  {
    id: 1,
    title: "Kaggle竞赛大师之路",
    description: "从新手到Kaggle Grandmaster的完整学习路径",
    courses: 8,
    duration: "3个月",
    students: 2400,
    difficulty: "初级到高级",
    icon: "🏆",
  },
  {
    id: 2,
    title: "全栈开发工程师",
    description: "掌握前后端开发，成为全栈工程师",
    courses: 12,
    duration: "6个月",
    students: 3200,
    difficulty: "中级",
    icon: "💻",
  },
  {
    id: 3,
    title: "AI工程师养成计划",
    description: "深入学习AI技术，成为AI领域专家",
    courses: 10,
    duration: "4个月",
    students: 1800,
    difficulty: "高级",
    icon: "🤖",
  },
]

const categories = [
  "全部",
  "Machine Learning",
  "Deep Learning",
  "Web Development",
  "Blockchain",
  "Data Science",
  "AI/LLM",
]
const levels = ["全部", "初级", "中级", "高级"]

export default function LearnPage() {
  const { user, isLoading } = useAuth()
  const [searchQuery, setSearchQuery] = useState("")
  const [selectedCategory, setSelectedCategory] = useState("全部")
  const [selectedLevel, setSelectedLevel] = useState("全部")

  const filteredCourses = mockCourses.filter((course) => {
    const matchesSearch =
      course.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      course.instructor.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesCategory = selectedCategory === "全部" || course.category === selectedCategory
    const matchesLevel = selectedLevel === "全部" || course.level === selectedLevel

    return matchesSearch && matchesCategory && matchesLevel
  })

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center pt-20">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white"></div>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center pt-20">
        <div className="glass border-white/20 p-8 text-center max-w-md mx-auto rounded-lg">
          <h2 className="text-2xl font-bold text-white mb-4">请先登录</h2>
          <p className="text-white/70 mb-6">您需要登录才能访问学习中心</p>
          <Link href="/auth/login">
            <Button className="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700">
              前往登录
            </Button>
          </Link>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen pt-20">
      <div className="container mx-auto px-4 py-8">
        {/* 头部 */}
        <motion.div initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} className="text-center mb-12">
          <h1 className="text-responsive-4xl font-bold mb-4 text-gradient-animate">学习中心</h1>
          <p className="text-responsive-xl text-gray-200 mb-8">提升技能，征服竞赛，成为技术大师</p>

          {/* 搜索和筛选 */}
          <div className="max-w-4xl mx-auto">
            <div className="flex flex-col md:flex-row gap-4 mb-6">
              <div className="flex-1 relative">
                <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-300 w-5 h-5" />
                <Input
                  placeholder="搜索课程、讲师..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-12 glass-light border-0 text-white placeholder-gray-400"
                />
              </div>
              <div className="flex gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  className="bg-transparent text-gray-200 border-gray-500 hover:border-blue-400 hover:text-blue-300"
                >
                  <Filter className="w-4 h-4 mr-2" />
                  筛选
                </Button>
              </div>
            </div>

            {/* 分类标签 */}
            <div className="flex flex-wrap justify-center gap-2 mb-4">
              {categories.map((category) => (
                <motion.div key={category} whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                  <Badge
                    variant={selectedCategory === category ? "default" : "outline"}
                    className={`cursor-pointer transition-all duration-300 ${
                      selectedCategory === category
                        ? "bg-blue-500 text-white"
                        : "text-gray-200 border-gray-500 hover:border-blue-400 hover:text-blue-300"
                    }`}
                    onClick={() => setSelectedCategory(category)}
                  >
                    {category}
                  </Badge>
                </motion.div>
              ))}
            </div>

            {/* 难度标签 */}
            <div className="flex justify-center gap-2">
              {levels.map((level) => (
                <motion.div key={level} whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                  <Badge
                    variant={selectedLevel === level ? "default" : "outline"}
                    className={`cursor-pointer transition-all duration-300 ${
                      selectedLevel === level
                        ? "bg-purple-500 text-white"
                        : "text-gray-200 border-gray-500 hover:border-purple-400 hover:text-purple-300"
                    }`}
                    onClick={() => setSelectedLevel(level)}
                  >
                    {level}
                  </Badge>
                </motion.div>
              ))}
            </div>
          </div>
        </motion.div>

        {/* 主要内容 */}
        <Tabs defaultValue="courses" className="w-full">
          <TabsList className="grid w-full grid-cols-3 glass mb-8">
            <TabsTrigger value="courses" className="text-gray-200">
              课程
            </TabsTrigger>
            <TabsTrigger value="paths" className="text-gray-200">
              学习路径
            </TabsTrigger>
            <TabsTrigger value="progress" className="text-gray-200">
              我的进度
            </TabsTrigger>
          </TabsList>

          {/* 课程列表 */}
          <TabsContent value="courses">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredCourses.map((course, index) => (
                <motion.div
                  key={course.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: index * 0.1 }}
                >
                  <Card className="glass border-0 card-hover h-full">
                    <div className="relative">
                      <img
                        src={course.thumbnail || "/placeholder.svg"}
                        alt={course.title}
                        className="w-full h-48 object-cover rounded-t-lg"
                      />
                      <div className="absolute top-3 left-3">
                        <Badge
                          className={`${course.price === "免费" ? "bg-green-500/20 text-green-400" : "bg-blue-500/20 text-blue-400"}`}
                        >
                          {course.price}
                        </Badge>
                      </div>
                      <div className="absolute top-3 right-3">
                        <Badge variant="outline" className="text-gray-200 border-gray-500">
                          {course.level}
                        </Badge>
                      </div>
                      {course.progress > 0 && (
                        <div className="absolute bottom-3 left-3 right-3">
                          <Progress value={course.progress} className="h-1" />
                        </div>
                      )}
                    </div>

                    <CardContent className="p-4">
                      <h3 className="font-semibold text-lg mb-2 line-clamp-2 text-white hover:text-blue-400 transition-colors">
                        {course.title}
                      </h3>

                      <div className="flex items-center gap-2 mb-3">
                        <Avatar className="w-6 h-6">
                          <AvatarImage src={course.avatar || "/placeholder.svg"} />
                          <AvatarFallback className="text-xs">{course.instructor[0]}</AvatarFallback>
                        </Avatar>
                        <span className="text-sm text-gray-300">{course.instructor}</span>
                      </div>

                      <p className="text-sm text-gray-300 mb-3 line-clamp-2">{course.description}</p>

                      <div className="flex items-center justify-between text-sm text-gray-400 mb-3">
                        <div className="flex items-center gap-1">
                          <Clock className="w-4 h-4" />
                          <span>{course.duration}</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <Users className="w-4 h-4" />
                          <span>{course.students.toLocaleString()}</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <Star className="w-4 h-4 text-yellow-400" />
                          <span>{course.rating}</span>
                        </div>
                      </div>

                      <div className="flex flex-wrap gap-1 mb-4">
                        {course.tags.map((tag) => (
                          <Badge key={tag} variant="outline" className="text-xs text-gray-300 border-gray-600">
                            {tag}
                          </Badge>
                        ))}
                      </div>

                      <div className="flex gap-2">
                        <Button
                          size="sm"
                          className="flex-1 bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600"
                        >
                          <Play className="w-4 h-4 mr-1" />
                          {course.progress > 0 ? "继续学习" : "开始学习"}
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          className="bg-transparent text-gray-200 border-gray-500 hover:border-blue-400 hover:text-blue-300"
                        >
                          详情
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                </motion.div>
              ))}
            </div>
          </TabsContent>

          {/* 学习路径 */}
          <TabsContent value="paths">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {mockPaths.map((path, index) => (
                <motion.div
                  key={path.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: index * 0.1 }}
                >
                  <Card className="glass border-0 card-hover h-full">
                    <CardHeader>
                      <div className="flex items-center gap-3 mb-2">
                        <div className="text-3xl">{path.icon}</div>
                        <div>
                          <CardTitle className="text-lg text-white">{path.title}</CardTitle>
                          <p className="text-sm text-gray-300">{path.description}</p>
                        </div>
                      </div>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-3 mb-4">
                        <div className="flex justify-between text-sm">
                          <span className="text-gray-400">课程数量</span>
                          <span className="text-white">{path.courses} 门课程</span>
                        </div>
                        <div className="flex justify-between text-sm">
                          <span className="text-gray-400">预计时长</span>
                          <span className="text-white">{path.duration}</span>
                        </div>
                        <div className="flex justify-between text-sm">
                          <span className="text-gray-400">学习人数</span>
                          <span className="text-white">{path.students.toLocaleString()}</span>
                        </div>
                        <div className="flex justify-between text-sm">
                          <span className="text-gray-400">难度</span>
                          <Badge variant="outline" className="text-gray-300 border-gray-600">
                            {path.difficulty}
                          </Badge>
                        </div>
                      </div>
                      <Button className="w-full bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600">
                        开始学习路径
                      </Button>
                    </CardContent>
                  </Card>
                </motion.div>
              ))}
            </div>
          </TabsContent>

          {/* 我的进度 */}
          <TabsContent value="progress">
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
              {/* 学习统计 */}
              <div className="lg:col-span-1">
                <Card className="glass border-0 card-hover mb-6">
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2 text-white">
                      <TrendingUp className="w-5 h-5 text-green-400" />
                      学习统计
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="text-center">
                      <div className="text-3xl font-bold text-blue-400 mb-2">12</div>
                      <div className="text-sm text-gray-300">已完成课程</div>
                    </div>
                    <div className="text-center">
                      <div className="text-3xl font-bold text-green-400 mb-2">156h</div>
                      <div className="text-sm text-gray-300">总学习时长</div>
                    </div>
                    <div className="text-center">
                      <div className="text-3xl font-bold text-purple-400 mb-2">8</div>
                      <div className="text-sm text-gray-300">获得证书</div>
                    </div>
                  </CardContent>
                </Card>

                <Card className="glass border-0 card-hover">
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2 text-white">
                      <Award className="w-5 h-5 text-yellow-400" />
                      最近成就
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    {[
                      { title: "机器学习专家", desc: "完成ML基础课程", icon: "🤖" },
                      { title: "代码忍者", desc: "连续学习7天", icon: "🥷" },
                      { title: "知识探索者", desc: "学习3个不同领域", icon: "🔍" },
                    ].map((achievement, index) => (
                      <div key={index} className="flex items-center gap-3 p-2 rounded-lg bg-white/5">
                        <div className="text-2xl">{achievement.icon}</div>
                        <div>
                          <div className="font-medium text-white">{achievement.title}</div>
                          <div className="text-xs text-gray-400">{achievement.desc}</div>
                        </div>
                      </div>
                    ))}
                  </CardContent>
                </Card>
              </div>

              {/* 正在学习的课程 */}
              <div className="lg:col-span-2">
                <h3 className="text-xl font-bold mb-4 text-white">正在学习</h3>
                <div className="space-y-4">
                  {mockCourses
                    .filter((course) => course.progress > 0)
                    .map((course, index) => (
                      <motion.div
                        key={course.id}
                        initial={{ opacity: 0, x: 20 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ delay: index * 0.1 }}
                      >
                        <Card className="glass border-0 card-hover">
                          <CardContent className="p-4">
                            <div className="flex items-center gap-4">
                              <img
                                src={course.thumbnail || "/placeholder.svg"}
                                alt={course.title}
                                className="w-20 h-20 object-cover rounded-lg"
                              />
                              <div className="flex-1">
                                <h4 className="font-semibold text-white mb-1">{course.title}</h4>
                                <p className="text-sm text-gray-300 mb-2">{course.instructor}</p>
                                <div className="flex items-center gap-4 mb-2">
                                  <span className="text-sm text-gray-400">进度: {course.progress}%</span>
                                  <div className="flex items-center gap-1 text-sm text-gray-400">
                                    <Clock className="w-4 h-4" />
                                    <span>{course.duration}</span>
                                  </div>
                                </div>
                                <Progress value={course.progress} className="mb-2" />
                              </div>
                              <Button
                                size="sm"
                                className="bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600"
                              >
                                继续学习
                              </Button>
                            </div>
                          </CardContent>
                        </Card>
                      </motion.div>
                    ))}
                </div>
              </div>
            </div>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  )
}
